<?php
/**
 * @copyright  For copyright and license information, read the COPYING.txt file.
 * @link       /COPYING.txt
 * @license    Academic Free License (AFL 3.0)
 * @package     default_default
 */

/** @var Mage_Adminhtml_Block_System_Config_System_Storage_Media_Synchronize $this */
?>

<script type="text/javascript">
//<![CDATA[
    Validation.add('required-synchronize', '<?php echo Mage::helper('core')->jsQuoteEscape($this->__('Synchronization is required.')) ?>', function(){
        storage = getConnectionName(
            $('system_media_storage_configuration_media_storage').value,
            $('system_media_storage_configuration_media_database').value
        );

        return allowedStorages.include(storage);
    });

    defaultValues   = [];
    defaultValues['system_media_storage_configuration_media_storage']   = $('system_media_storage_configuration_media_storage').value;
    defaultValues['system_media_storage_configuration_media_database']  = $('system_media_storage_configuration_media_database').value;

    allowedStorages = [];
    addAllowedStorage(
        $('system_media_storage_configuration_media_storage').value,
        $('system_media_storage_configuration_media_database').value
    );

    <?php $syncStorageParams = $this->getSyncStorageParams() ?>
    addAllowedStorage(<?php echo $syncStorageParams['storage_type'] ?>, '<?php echo $syncStorageParams['connection_name'] ?>');

    function getConnectionName(storageType, connection)
    {
        if (storageType == 0) {
            return storageType;
        } else if (connection != '') {
            return storageType + '_' + connection;
        }

        return '';
    }

    function addAllowedStorage(storageType, connection)
    {
        storage = getConnectionName(storageType, connection);

        if (storage != '' && !allowedStorages.include(storage)) {
            allowedStorages.push(storage);
        }
    }

    function checkButtonState(event) {
        var element = Event.element(event);

        defaultStorage = getConnectionName(
            defaultValues['system_media_storage_configuration_media_storage'],
            defaultValues['system_media_storage_configuration_media_database']
        );

        storage = getConnectionName(
            $('system_media_storage_configuration_media_storage').value,
            $('system_media_storage_configuration_media_database').value
        );

        if (defaultStorage != storage) {
            enableSyncButton();
        } else {
            disableSyncButton();
        }
    }

    function enableStorageSelection() {
        $('system_media_storage_configuration_media_storage').enable('enabled');
        $('system_media_storage_configuration_media_database').enable('enabled');
    }

    function disableStorageSelection() {
        $('system_media_storage_configuration_media_storage').disable('disabled');
        $('system_media_storage_configuration_media_database').disable('disabled');
    }

    function enableSyncButton() {
        Form.Element.enable('synchronize_button');
        $('synchronize_button').removeClassName('disabled');
    }

    function disableSyncButton() {
        Form.Element.disable('synchronize_button');
        $('synchronize_button').addClassName('disabled');
    }

    Event.observe(window, 'load', function(){
        disableStorageSelection();
        disableSyncButton();
        checkStatus();
    });
    $('system_media_storage_configuration_media_storage').observe('change', checkButtonState);
    $('system_media_storage_configuration_media_database').observe('change', checkButtonState);

    function checkStatus() {
        var u = new Ajax.PeriodicalUpdater('', '<?php echo $this->getAjaxStatusUpdateUrl() ?>', {
            method:     'get',
            frequency:  5,
            loaderArea: false,

            onSuccess: function(transport) {
                var response;

                try {
                    response = transport.responseJSON || transport.responseText.evalJSON(true) || {};
                    if (response.state == '<?php echo Mage_Core_Model_File_Storage_Flag::STATE_RUNNING ?>'
                        && response.message
                    ) {
                        if ($('sync_span').hasClassName('no-display')) {
                            $('sync_span').removeClassName('no-display');
                            $('sync_message_span').update(response.message);
                        }
                    } else {
                        u.stop();
                        enableStorageSelection();
                        $('sync_span').addClassName('no-display');

                        if (response.state == '<?php echo Mage_Core_Model_File_Storage_Flag::STATE_NOTIFIED ?>') {
                            if (response.html && response.html != '') {
                                $$('div.notification-global').each(function(e) {
                                    if (!e.hasClassName('notification-global-notice')) {
                                        e.hide();
                                    }
                                });

                                Element.insert($('anchor-content'), {'before': response.html});
                            }

                            if (response.has_errors) {
                                enableSyncButton();
                            } else {
                                addAllowedStorage(
                                    $('system_media_storage_configuration_media_storage').value,
                                    $('system_media_storage_configuration_media_database').value
                                );
                            }
                        }
                    }
                } catch (e) {
                    response = {};
                }
            }
        });
    }

    function synchronize() {
        var advice = Validation.getAdvice('required-synchronize', $('synchronize-validation-input'));
        if (advice) {
            advice.hide();
        }
        params = {
            storage:    $('system_media_storage_configuration_media_storage').value,
            connection: $('system_media_storage_configuration_media_database').value
        }

        new Ajax.Request('<?php echo $this->getAjaxSyncUrl() ?>', {
            parameters:     params,
            loaderArea:     false,
            asynchronous:   true
        });

        window.setTimeout('checkStatus()', 2011);

        disableStorageSelection();
        disableSyncButton();
    }
//]]>
</script>

<?php echo $this->getButtonHtml() ?><span class="sync-indicator no-display" id="sync_span"><img alt="Synchronize" style="margin:0 5px" src="<?php echo $this->getSkinUrl('images/process_spinner.gif') ?>"/><span id="sync_message_span"></span></span>
<input type="hidden" id="synchronize-validation-input" class="required-synchronize no-display"/>
